#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <vector>

typedef void (*fun)();
std::vector<fun> funs; 

void fun1()
{
  printf("这是临时任务1\n");
}

void fun2()
{
  printf("这是临时任务2\n");
}

void Load()
{
  funs.push_back(fun1);
  funs.push_back(fun2);
}

void dofun()
{
  if(funs.empty())
    Load();
  for(auto x : funs)
    x();
}

int main(int argc, char* argv[], char* env[])
{
  (void)argc;
  (void)argv;
  (void)env;

  const char* us = getenv("USER");

  if(!strcmp("zy", us))
  {
    

    pid_t pid = fork();
    if(pid == 0)
    {
      printf("child is run, pid is : %d\n", getpid());
      sleep(5);
      exit(1);
    }
    else 
    {
      int status = 0;
      int cpid = 0;
      do 
      {
        cpid =  waitpid(pid, &status, WNOHANG);
        if(cpid == 0)
          printf("child is running\n");
        dofun();
      }while(cpid == 0);

      if(WIFEXITED(status))
        printf("child run success, child return code is :%d\n", WEXITSTATUS(status));

    }



    //wait() 和 waitpid()
    //int pid = fork();

    //if(pid == 0)
    //{
    //  //int num = 5;
    //  //while(num--)
    //  //{
    //    printf("子进程运行中, pid:%d\n", getpid());
    //    sleep(5);
    //  //}
    //}
    //else 
    //{
    //  //while(1)
    //  //{
    //    int status = 0;
    //    printf("this is test for wait\n");
    //    //sleep(5);
    //    
    //    int spid = waitpid(pid, &status, 0);
    //    printf("子进程的pid:%d\n", spid);
    //    if(WIFEXITED(status))
    //      printf("process success,child return code: %d\n", WEXITSTATUS(status));
    //    

    //    //int spid = wait(NULL);
    //    //printf("子进程的pid为: %d\n", spid);
    //  //}
    //}


    //_exit() 与 exit()
    //printf("刷新缓冲区");
    //_exit(0);
    //exit(0);
    
    //strerror的使用
    //for(int i = 0; i <= 200; i++)
    //{
    //  printf("%d: %s\n", i, strerror(i));
    //}


    //小复习
    //int id = fork();
    //if(id == 0)
    //{
    //  printf("son: pid=%d\n", getpid());
    //  sleep(1);
    //  exit(0);
    //}
    //else if(id > 0)
    //{  
    //  printf("parent: pid=%d\n", getpid());
    //  sleep(1);
    //  printf("%s\n", strerror(0));
    //}
    //else 
    //{
    //  //perror("fork");
    //  printf("%s fork error\n", __FUNCTION__);
    //  exit(1); //return 1;
    //}
  }
  return 0;
}
